package com.mayikt.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseResponse;
import com.mayikt.base.BaseWebController;
import com.mayikt.constants.Constants;
import com.mayikt.core.util.VerifyCodeUtil;
import com.mayikt.feign.MemberRegisterServiceFeign;
import com.mayikt.member.controller.res.vo.RegisterVo;
import com.mayikt.member.input.dto.UserInpDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class RegisterController extends BaseWebController {
    private static final String MB_REGISTER_FTL = "member/register";
    private static final String MB_LOGIN_FTL = "member/login";
    @Autowired
    private MemberRegisterServiceFeign memberRegisterServiceFeign;

    @GetMapping("/register.html")
    public String getRegister(){
        return MB_REGISTER_FTL;
    }

    @PostMapping("/register.html")
    public String postRegister(@ModelAttribute(value = "registerVo")@Validated RegisterVo registerVo,
                               BindingResult bindingResult,
                               Model model,
                               HttpSession httpSession){
        if (bindingResult.hasErrors()){
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            setErrorMsg(model, errorMsg);
            return MB_REGISTER_FTL;
        }
        Boolean checkBoolean = VerifyCodeUtil.checkVerify(registerVo.getGraphicCode(), httpSession);
        if (!checkBoolean){
            setErrorMsg(model,"验证码错误");
            return MB_REGISTER_FTL;
        }
        UserInpDTO userInpDTO = new UserInpDTO();
        BeanUtils.copyProperties(registerVo,userInpDTO);
        BaseResponse<JSONObject> register = memberRegisterServiceFeign.register(userInpDTO, registerVo.getRegistCode());
        if (!Constants.HTTP_RES_CODE_200.equals(register.getCode())){
//            手机号已存在
            setErrorMsg(model,register.getMsg());
            return MB_REGISTER_FTL;
        }
//        注册成功，跳转登陆页面
        return MB_LOGIN_FTL;
    }
}
